#!/bin/bash
# This is a ShellScript For Auto Install LNMP and Moodle on Debian
# Add executive privilege
# chmod 755 debian.sh
# Powered by hongm
# Visted http://hongm.emoodle.org
# Modify 2020-06-15
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

## Moodle Version##
Moodle_Version="3.11"

##Moodle Code##
MoodleFileName="moodle_git.tgz"

##Moodle WebSite Home Directory##
Default_Moodle_Dir="/www"

##MariaDB Root Password and Dir##
DB_Root_PWD="123456"
DB_Data_Dir="${Default_Moodle_Dir}/mariadb"

##Other##
MoodleAdminEmail="admin@163.com"


# Check if user is root
if [ $(id -u) != "0" ]; then
    echo "Error: You must be root to run this script"
    exit 1
fi
IP=$( cat /etc/network/interfaces | grep address | awk -F" " '{print $2}' | awk -F"/" '{print $1}' )
cur_dir=$(pwd)
if [ -s ${cur_dir}/moodle-install.log ]; then
    mv ${cur_dir}/moodle-install.log ${cur_dir}/moodle-install.last.log
fi

#check memfree
MemTotal=`free -m | grep Mem | awk '{print  $2}'`
InnodbBufferPoolSize=64M
InnodbLogFileSize=16M
PHPFPM_Max=10
PHPFPM_Min=4
if [[ ${MemTotal} -gt 1000 && ${MemTotal} -lt 2000 ]]; then
    InnodbBufferPoolSize=128M
    InnodbLogFileSize=32M
    PHPFPM_Max=20
    PHPFPM_Min=10
 elif [[ ${MemTotal} -ge 2000 && ${MemTotal} -lt 4000 ]]; then
    InnodbBufferPoolSize=256M
    InnodbLogFileSize=64M
    PHPFPM_Max=40
    PHPFPM_Min=20
 elif [[ ${MemTotal} -ge 4000 && ${MemTotal} -lt 8000 ]]; then
    InnodbBufferPoolSize=512M
    InnodbLogFileSize=128M
    PHPFPM_Max=60
    PHPFPM_Min=30
 elif [[ ${MemTotal} -ge 8000 ]]; then
    InnodbBufferPoolSize=1024M
    InnodbLogFileSize=256M
    PHPFPM_Max=80
    PHPFPM_Min=40
fi
PHPFPM_Start=$(($PHPFPM_Min+($PHPFPM_Max-$PHPFPM_Min)/2))

clear
#which Debian Version do you want to Update?
if grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
    Debian_OldVersion=`cat /etc/debian_version`
    echo -e " \e[0;33mYour Debian Version is \e[0;31m$Debian_OldVersion\e[0m"
    if echo ${Debian_OldVersion} | grep -Eqi '^6.'; then
        echo -e "   \e[0;31m Please run ./upgrade.sh\e[0m"
        exit 1
     elif echo ${Debian_OldVersion} | grep -Eqi '^7.'; then
        echo -e "   \e[0;31m Please run ./upgrade.sh\e[0m"
        exit 1
     elif echo ${Debian_OldVersion} | grep -Eqi '^8.'; then
        echo -e "   \e[0;31m Please run ./debian8.sh\e[0m"
        exit 1
     elif echo ${Debian_OldVersion} | grep -Eqi '^9.'; then
        echo -e "   \e[0;31m Please run ./debian10.sh\e[0m"
        exit 1
    fi 
 else
    echo -e " \e[0;31mYour OS is not Debian!\e[0m"
    exit 1
fi

#Moodle_Selection
    MoodleVer_major=`echo ${Moodle_Version} | cut -d "." -f1`
    MoodleVer_minor=`echo ${Moodle_Version} | cut -d "." -f2`
    MoodleVer=${Moodle_Version:0:1}${Moodle_Version:2:1}
    MoodleVer8=${MoodleVer_minor}
    MoodleVer7=$[${MoodleVer_minor}-1]
    MoodleVer6=$[${MoodleVer_minor}-2]
    MoodleVer5=$[${MoodleVer_minor}-3]
    MoodleVer4=$[${MoodleVer_minor}-4]
    MoodleVer3=$[${MoodleVer_minor}-5]
    MoodleVer2=$[${MoodleVer_minor}-6]
    MoodleVer1=$[${MoodleVer_minor}-7]
    #which Moodle Version do you want to install?
    echo "==========================="
    Moodle_Ver8=${MoodleVer_major}.${MoodleVer8}
    Moodle_Ver7=${MoodleVer_major}.${MoodleVer7}
    Moodle_Ver6=${MoodleVer_major}.${MoodleVer6}
    Moodle_Ver5=${MoodleVer_major}.${MoodleVer5}
    Moodle_Ver4=${MoodleVer_major}.${MoodleVer4}
    Moodle_Ver3=${MoodleVer_major}.${MoodleVer3}
    Moodle_Ver2=${MoodleVer_major}.${MoodleVer2}
    Moodle_Ver1=${MoodleVer_major}.${MoodleVer1}
    MoodleSelect="8"
    echo -e " \e[0;33mYou have many options for your Moodle install.\e[0m"
    echo -e "   \e[0;31m1\e[0m: Install Moodle ${Moodle_Ver1} (Legacy releases)"
    echo -e "   \e[0;31m2\e[0m: Install Moodle ${Moodle_Ver2} (Legacy releases)"
    echo -e "   \e[0;31m3\e[0m: Install Moodle ${Moodle_Ver3} (Legacy releases)"
    echo -e "   \e[0;31m4\e[0m: Install Moodle ${Moodle_Ver4} (Legacy releases)"
    echo -e "   \e[0;31m5\e[0m: Install Moodle ${Moodle_Ver5} (Security-only-supported releases)"
    echo -e "   \e[0;31m6\e[0m: Install Moodle ${Moodle_Ver6} (Security-only-supported releases)"
    echo -e "   \e[0;31m7\e[0m: Install Moodle ${Moodle_Ver7} (Other supported releases)"
    echo -e "   \e[0;31m8\e[0m: Install Moodle ${Moodle_Ver8} (Latest release)\e[44;37m(Default)\e[0m"
    read -p "Enter your choice (1, 2, 3, 4, 5, 6, 7 or 8): " MoodleSelect
    if [ "${MoodleSelect}" = "" ]; then
        MoodleSelect="8"
    fi
    CurMoodleVer=${MoodleVer_major}$[MoodleVer${MoodleSelect}]
    MoodleVer="MOODLE_${CurMoodleVer}_STABLE"
    Moodle_Version=${MoodleVer_major}.$[MoodleVer${MoodleSelect}]
    #echo -e " \e[0;32mNo input,You will install \e[0;31mMoodle ${Moodle_Version}\e[0m"

echo -e "\e[0;33mYou will install:\e[0m"
echo -e "    \e[0;31mNginx\t\e[0;32m1.12\e[0m"
echo -e "    \e[0;31mMariaDB\t\e[0;32m10.3\e[0m"
echo -e "    \e[0;31mPHP\t\t\e[0;32m7.3\e[0m"
echo -e "    \e[0;31mMoodle\t\e[0;32m${Moodle_Version}\e[0m"
echo "Press any key to install...or Press Ctrl+c to cancel"
OLDCONFIG=`stty -g`
stty -icanon -echo min 1 time 0
dd count=1 2>/dev/null
stty ${OLDCONFIG}

echo -e " \e[0;32m[+] System Upgrade...\e[0m"
Debian_Ver="10"
mv /etc/apt/sources.list /etc/apt/sources.list.bak
echo 'deb http://mirrors.ustc.edu.cn/debian/ buster main' > /etc/apt/sources.list
echo 'deb-src http://mirrors.ustc.edu.cn/debian/ buster main' >> /etc/apt/sources.list
echo 'deb http://mirrors.ustc.edu.cn/debian/ buster-proposed-updates main' >> /etc/apt/sources.list
echo 'deb-src http://mirrors.ustc.edu.cn/debian/ buster-proposed-updates main' >> /etc/apt/sources.list
echo 'deb http://mirrors.ustc.edu.cn/debian/ buster-updates main' >> /etc/apt/sources.list
echo 'deb-src http://mirrors.ustc.edu.cn/debian/ buster-updates main' >> /etc/apt/sources.list
echo 'deb http://mirrors.ustc.edu.cn/debian-security/ buster/updates main' >> /etc/apt/sources.list
echo 'deb-src http://mirrors.ustc.edu.cn/debian-security/ buster/updates main' >> /etc/apt/sources.list
NginxConfigFile="/etc/nginx/nginx.conf"
NginxDefaultFile="/etc/nginx/sites-available/default"
Nginx_User="www-data"
Nginx_Con1="include /etc/nginx/modules-enabled/*.conf;"
Nginx_Con2="include /etc/nginx/sites-enabled/*;"
MariaDBConfigFile="/etc/mysql/mariadb.conf.d/50-server.cnf"
MariaDBVersion='10.3'
PHPConfigFile="/etc/php/7.3/fpm/php.ini"
PHPCliConfigFile="/etc/php/7.3/cli/php.ini"
PHPFPMConfigFile="/etc/php/7.3/fpm/pool.d/www.conf"
PHPFPMService='php7.3-fpm'
PHPFPMProgram='php-fpm7.3'
apt-get update && apt-get -y dist-upgrade && apt-get -y autoremove && apt-get autoclean

#Check Mirror
Download_Mirror = 'http://hongm.emoodle.org:8080/down'
if [ "${Download_Mirror}" = "http://hongm.emoodle.org:8080/down" ]; then
    mirror_code=`curl -o /dev/null -m 20 --connect-timeout 20 -sk -w %{http_code} http://hongm.emoodle.org:8080/down/`
    if [ "${mirror_code}" != "200" ]; then
        mirror_code=`curl -o /dev/null -m 20 --connect-timeout 20 -sk -w %{http_code} https://study.wjszzx.com.cn/soft/`
        if [ "${mirror_code}" = "200" ]; then
            echo "Change to mirror https://study.wjszzx.com.cn/soft"
            Download_Mirror='https://study.wjszzx.com.cn/soft'
        else
            echo "Dwonload Server Error!"
            exit 1
        fi
    fi
fi

function InstallLNMP()
{
    ulimit -v unlimited
    if cat /etc/security/limits.conf | grep "* soft nproc 65535" ; then
       echo "limits.conf has been modified"
     else
        echo "* soft nproc 65535" >>/etc/security/limits.conf
        echo "* hard nproc 65535" >>/etc/security/limits.conf
        echo "* soft nofile 65535" >>/etc/security/limits.conf
        echo "* hard nofile 65535" >>/etc/security/limits.conf
        echo "fs.file-max=65535" >> /etc/sysctl.conf
        echo deadline >/sys/block/sda/queue/scheduler
    fi

    echo -e " \e[0;31m[+] Apt-get installing Nginx+MariaDB+PHP ...\e[0m"
    { \
	echo "mariadb-server-${MariaDBVersion}" mysql-server/root_password password "${DB_Root_PWD}"; \
	echo "mariadb-server-${MariaDBVersion}" mysql-server/root_password_again password "${DB_Root_PWD}"; \
    } | debconf-set-selections
    apt-get -y install nginx mariadb-server php7.3-fpm php7.3-mysql php7.3-gd php7.3-xsl php7.3-xmlrpc php7.3-curl php7.3-intl php7.3-tidy php7.3-mbstring php7.3-soap php7.3-zip php7.3-ldap --force-yes

    echo -e " \e[0;32m[+] Modify MariaDB config ...\e[0m"
    cat > /tmp/mariadb_sec_script<<EOF
delete from mysql.user where not (user='root') and not (user='debian-sys-maint');
delete from mysql.user where user='root' and password='';
grant all on moodle.* to 'moodle'@'localhost' identified by '${DB_Root_PWD}';
grant all on moodle.* to 'moodle'@'127.0.0.1' identified by '${DB_Root_PWD}';
flush privileges;
CREATE DATABASE moodle DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
EOF
    /usr/bin/mysql -u root -p${DB_Root_PWD} -h localhost < /tmp/mariadb_sec_script
    systemctl stop mysql.service
    mkdir -p ${DB_Data_Dir}/logs
    cp -a /var/lib/mysql ${DB_Data_Dir}/data
    chown -R mysql:mysql ${DB_Data_Dir}/data
    chown -R mysql:mysql ${DB_Data_Dir}/logs

    cat > ${MariaDBConfigFile}<<EOF
[client]
port		= 3306
socket		= /var/run/mysqld/mysqld.sock

[mysqld]
port	= 3306
socket	= /var/run/mysqld/mysqld.sock
user	= mysql
basedir	= /usr
datadir	= ${DB_Data_Dir}/data
tmpdir	= /tmp
pid-file  = ${DB_Data_Dir}/data/mariadb.pid
log_error = ${DB_Data_Dir}/logs/mariadb.err
skip-external-locking
key_buffer_size = 16M
max_allowed_packet = 1M
table_open_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
thread_cache_size = 8
query_cache_size = 8M
tmp_table_size = 16M
table_open_cache = 64
explicit_defaults_for_timestamp = true
#skip-networking
max_connections = 500
max_connect_errors = 100
open_files_limit = 65535
log_bin=${DB_Data_Dir}/logs/mariadb-bin
log_bin_index= ${DB_Data_Dir}/logs/mariadb-bin.index
binlog_format=mixed
expire_logs_days = 10
max_binlog_size = 100M
server-id	= 1
default_storage_engine = InnoDB
innodb_data_home_dir = ${DB_Data_Dir}/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = ${DB_Data_Dir}/data
innodb_buffer_pool_size = ${InnodbBufferPoolSize}
innodb_log_file_size = ${InnodbLogFileSize}
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 2
innodb_lock_wait_timeout= 50
innodb_file_per_table	= 1
innodb_open_files	= 2000
innodb_io_capacity	= 400
innodb_flush_method	= O_DIRECT
innodb_large_prefix	= 1
character-set-server 	= utf8mb4
collation-server 	= utf8mb4_unicode_ci

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash

[myisamchk]
key_buffer_size = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout
EOF
    systemctl start mysql.service
    systemctl restart mysql.service

    echo -e " \e[0;32m[+] Modify PHP config ...\e[0m"
    sed -i 's/post_max_size = 8M/post_max_size = 2048M/g' ${PHPConfigFile}
    sed -i 's/upload_max_filesize = 2M/upload_max_filesize = 2048M/g' ${PHPConfigFile}
    sed -i 's/;date.timezone =/date.timezone = PRC/g' ${PHPConfigFile}
    sed -i 's/short_open_tag = Off/short_open_tag = On/g' ${PHPConfigFile}
    sed -i 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/g' ${PHPConfigFile}
    sed -i 's/max_execution_time = 30/max_execution_time = 300/g' ${PHPConfigFile}
    sed -i 's/max_input_time = 60/max_input_time = 600/g' ${PHPConfigFile}
    sed -i 's/default_socket_timeout = 60/default_socket_timeout = 600/g' ${PHPConfigFile}
    sed -i 's/;max_input_vars = 1000/max_input_vars = 10000/g' ${PHPConfigFile}
    sed -i 's/memory_limit = 128M/memory_limit = 512M/g' ${PHPConfigFile}
    sed -i 's/;max_input_vars = 1000/max_input_vars = 10000/g' ${PHPCliConfigFile}
    cat >${PHPFPMConfigFile}<<EOF
[www]
user = ${Nginx_User}
group = ${Nginx_User}
listen = /var/run/php-fpm.sock
listen.owner = ${Nginx_User}
listen.group = ${Nginx_User}
listen.mode = 0666
pm = dynamic
pm.max_children = ${PHPFPM_Max}
pm.start_servers = ${PHPFPM_Start}
pm.min_spare_servers = ${PHPFPM_Min}
pm.max_spare_servers = ${PHPFPM_Max}
request_terminate_timeout = 100
request_slowlog_timeout = 0
slowlog = /var/log/phpslow.log
EOF

    echo -e " \e[0;32m[+] Modify Nginx config ...\e[0m"
    mv ${NginxConfigFile} ${NginxConfigFile}.bak
    cat > ${NginxConfigFile}<<EOF
user  ${Nginx_User};
worker_processes auto;
worker_rlimit_nofile  65535;
error_log  /var/log/nginx/error.log error;
pid        /var/run/nginx.pid;
${Nginx_Con1}
events {
    worker_connections  10240;
    use epoll;
    multi_accept on;
}
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    log_format  main  '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                      '\$status \$body_bytes_sent "\$http_referer" '
                      '"\$http_user_agent" "\$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    tcp_nopush     on;
    tcp_nodelay on;
    keepalive_timeout  65;
    types_hash_max_size 2048;
    server_tokens off;
    client_header_timeout 600;
    client_body_timeout 600;
    reset_timedout_connection on;
    send_timeout 600;
    client_max_body_size 2048m;
    client_body_buffer_size 512k;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
    server_names_hash_bucket_size 128;
    fastcgi_connect_timeout 600;
    fastcgi_send_timeout 600;
    fastcgi_read_timeout 600;
    fastcgi_buffer_size 256k;
    fastcgi_buffers 8 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    open_file_cache max=102400 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 1;
    gzip  on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 4;
    gzip_min_length  10240;
    gzip_buffers 8 16k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss ext/javascript;
    include /etc/nginx/conf.d/*.conf;
    ${Nginx_Con2}
}
EOF
    mv ${NginxDefaultFile} ${NginxDefaultFile}.bak
    echo "server {" > ${NginxDefaultFile}
    echo "    listen       80;" >> ${NginxDefaultFile}
    echo "    server_name  _;" >> ${NginxDefaultFile}
    echo "    root   ${Default_Moodle_Dir}/moodle;" >> ${NginxDefaultFile}
    echo "    index  index.php index.html index.htm;" >> ${NginxDefaultFile}
    echo "    location / {" >> ${NginxDefaultFile}
    echo '        try_files $uri $uri/ /index.html;' >> ${NginxDefaultFile}
    echo "    }" >> ${NginxDefaultFile}
    echo "    location ~ ^(.+\.php)(.*)$ {" >> ${NginxDefaultFile}
    echo "        fastcgi_split_path_info  ^(.+\.php)(.*)$;" >> ${NginxDefaultFile}
    echo "        fastcgi_pass   unix:/var/run/php-fpm.sock;" >> ${NginxDefaultFile}
    echo "        fastcgi_index  index.php;" >> ${NginxDefaultFile}
    echo "        include        fastcgi_params;" >> ${NginxDefaultFile}
    echo "        fastcgi_param   PATH_INFO       $fastcgi_path_info;" >> ${NginxDefaultFile}
    echo '        fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;' >> ${NginxDefaultFile}
    echo "    }" >> ${NginxDefaultFile}
    echo "}" >> ${NginxDefaultFile}
    mkdir -p /etc/nginx/ssl
    wget -c --progress=bar:force --no-check-certificate ${Download_Mirror}/ssl/server.crt -O /etc/nginx/ssl/server.crt
    wget -c --progress=bar:force --no-check-certificate ${Download_Mirror}/ssl/server.key -O /etc/nginx/ssl/server.key
    if [[ -s /etc/nginx/ssl/server.key && -s /etc/nginx/ssl/server.crt ]]; then
        echo "server {" >> ${NginxDefaultFile}
        echo "    listen       443 ssl;" >> ${NginxDefaultFile}
        echo "    ssl_certificate /etc/nginx/ssl/server.crt;" >> ${NginxDefaultFile}
        echo "    ssl_certificate_key /etc/nginx/ssl/server.key;" >> ${NginxDefaultFile}
        echo "    server_name  _;" >> ${NginxDefaultFile}
        echo "    root   ${Default_Moodle_Dir}/moodle;" >> ${NginxDefaultFile}
        echo "    index  index.php index.html index.htm;" >> ${NginxDefaultFile}
        echo "    location / {" >> ${NginxDefaultFile}
        echo '        try_files $uri $uri/ /index.html;' >> ${NginxDefaultFile}
        echo "    }" >> ${NginxDefaultFile}
        echo "    location ~ ^(.+\.php)(.*)$ {" >> ${NginxDefaultFile}
        echo "        fastcgi_split_path_info  ^(.+\.php)(.*)$;" >> ${NginxDefaultFile}
        echo "        fastcgi_pass   unix:/var/run/php-fpm.sock;" >> ${NginxDefaultFile}
        echo "        fastcgi_index  index.php;" >> ${NginxDefaultFile}
        echo "        include        fastcgi_params;" >> ${NginxDefaultFile}
        echo "        fastcgi_param   PATH_INFO       $fastcgi_path_info;" >> ${NginxDefaultFile}
        echo '        fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;' >> ${NginxDefaultFile}
        echo "    }" >> ${NginxDefaultFile}
        echo "}" >> ${NginxDefaultFile}
    fi

    systemctl restart nginx.service
    systemctl restart ${PHPFPMService}.service
    apt-get autoclean
}


function InstallMoodle()
{
    echo -e " \e[0;32m[+] Install Moodle Soucre...\e[0m"
    mkdir -p ${Default_Moodle_Dir}
    cd ${Default_Moodle_Dir}
    n=0
    while [ $n -le 8 -a ! -f ${Default_Moodle_Dir}/moodle/version.php ]
    do
        git clone -b ${MoodleVer} --depth=1 https://gitee.com/hongm/moodle.git
        n=$((n+1))
    done
    if [ $n -ge 8 ]; then
        echo "Network error! Please download moodle Code continue to install!"
        exit
     else
        sed -i 's#https://gitee.com/hongm/moodle.git#git://git.moodle.org/moodle.git#g' /www/moodle/.git/config
        cd ${Default_Moodle_Dir}/moodle && git pull
    fi
    Stable_Version=$( git branch -a | sed '$d' | sed -n '$p' | awk -F "_" '{print $2}' )
    git checkout -b MOODLE_${Stable_Version}_STABLE origin/MOODLE_${Stable_Version}_STABLE
    git branch -D master
    git pull --force
    cd ${cur_dir}
    echo '<?PHP  // Moodle configuration file' > ${Default_Moodle_Dir}/moodle/config.php
    echo 'unset($CFG);' >> ${Default_Moodle_Dir}/moodle/config.php
    echo 'global $CFG;' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG = new stdClass();' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->dbtype    = "mariadb";' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->dblibrary = "native";' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->dbhost    = "127.0.0.1";' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->dbname    = "moodle";' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->dbuser    = "moodle";' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->dbpass    = "'${DB_Root_PWD}'";' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->prefix    = "mdl_";' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->dboptions = array(' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '  "dbpersist" => 0,' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '  "dbport" => "",' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '  "dbsocket" => "",' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '  "dbcollation" => "utf8mb4_unicode_ci",' >> ${Default_Moodle_Dir}/moodle/config.php
    echo ');' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->wwwroot   = "http://'${IP}'";' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->dataroot  = "'${Default_Moodle_Dir}'/moodledata";' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->directorypermissions = 0700;' >> ${Default_Moodle_Dir}/moodle/config.php
    echo '$CFG->admin = "admin";' >> ${Default_Moodle_Dir}/moodle/config.php
    echo 'require_once(dirname(__FILE__) . "/lib/setup.php"); // Do not edit' >> ${Default_Moodle_Dir}/moodle/config.php
    mkdir -p ${Default_Moodle_Dir}/moodledata
    chown -R ${Nginx_User}:${Nginx_User} ${Default_Moodle_Dir}/moodle
    chown -R ${Nginx_User}:${Nginx_User} ${Default_Moodle_Dir}/moodledata
    chmod -R 0700 ${Default_Moodle_Dir}/moodle
    chmod -R 0700 ${Default_Moodle_Dir}/moodledata
    find ${Default_Moodle_Dir}/moodle -type f -exec chmod 0600 {} \;

    n=0
    while [ $n -le 8 -a ! -f ${DB_Data_Dir}/data/moodle/mdl_user.frm ]
    do
        sudo -u ${Nginx_User} /usr/bin/php ${Default_Moodle_Dir}/moodle/admin/cli/install_database.php --lang=zh_cn --adminpass=${DB_Root_PWD} --adminemail=${MoodleAdminEmail} --fullname=ITCenter --shortname=ITCenter --agree-license
        n=$((n+1))
    done
    if [ $n -ge 8 ]; then
        echo "Network error! Please continue to install http://${IP} in the browser!"
     else
        /usr/bin/mysql -u root -p${DB_Root_PWD} -h localhost -e "UPDATE moodle.mdl_config SET value='firstname,lastname' WHERE name='alternativefullnameformat';"
        /usr/bin/mysql -u root -p${DB_Root_PWD} -h localhost -e "UPDATE moodle.mdl_config SET value='0' WHERE name='defaulthomepage';"
        /usr/bin/mysql -u root -p${DB_Root_PWD} -h localhost -e "UPDATE moodle.mdl_config SET value='CN' WHERE name='country';"
        /usr/bin/mysql -u root -p${DB_Root_PWD} -h localhost -e "UPDATE moodle.mdl_config SET value='Asia/Shanghai' WHERE name='timezone';"
        /usr/bin/mysql -u root -p${DB_Root_PWD} -h localhost -e "UPDATE moodle.mdl_config SET value='' WHERE name='docroot';"
        echo "* * * * * /usr/bin/php /www/moodle/admin/cli/cron.php >/tmp/moodlecron.log" >> /var/spool/cron/crontabs/${Nginx_User}
        chown ${Nginx_User}:${Nginx_User} /var/spool/cron/crontabs/${Nginx_User}
        chmod 0600 /var/spool/cron/crontabs/${Nginx_User}
        wget -c --progress=bar:force --no-check-certificate ${Download_Mirror}/moodle/langpack/zh_cn_local.tar.gz
        if  [ -s zh_cn_local.tar.gz ]; then
            tar zxf zh_cn_local.tar.gz -C ${Default_Moodle_Dir}/moodledata/lang
            chown -R ${Nginx_User}:${Nginx_User} ${Default_Moodle_Dir}/moodledata/lang/zh_cn_local
            chmod -R 0700 ${Default_Moodle_Dir}/moodledata/lang/zh_cn_local
            rm -fr zh_cn_local.tar.gz
        fi
    fi
    if [ ! -f /usr/local/bin/moodle ]; then
        if [ ! -f ${cur_dir}/conf/init.d.moodle ]; then
            wget -c --progress=bar:force --no-check-certificate ${Download_Mirror}/moodle/imoodle/init.d.moodle -O /usr/local/bin/moodle
         else
            cp ${cur_dir}/conf/init.d.moodle /usr/local/bin/moodle
        fi
        if [ -f /usr/local/bin/moodle ]; then
            chmod 755 /usr/local/bin/moodle
        fi
    fi
}


Check_Nginx_Files()
{
    isNginx=""
    echo "============================== Check install =============================="
    echo "Checking ..."
    if [[ -s ${NginxConfigFile} && -s /usr/sbin/nginx ]]; then
        nginx -v 2>/dev/null
        if [ $? -eq 0 ] ; then
            Cur_Nginx_Version=$(nginx -v 2>&1 | cut -c22- | tr -d "[()a-zA-Z ]" )
         else
            Cur_Nginx_Version=""
        fi
        echo -e " \e[0;32mNginx-${Cur_Nginx_Version} OK\e[0m"
        isNginx="ok"
    else
        echo -e " \e[0;31mError: Nginx install failed.\e[0m"
    fi
}

Check_DB_Files()
{
    isDB=""
    if [[ -s /usr/bin/mysql && -s /usr/bin/mysqld_safe && -s ${MariaDBConfigFile} ]]; then
        Cur_MariaDB_Version=$(mysql -V 2>/dev/null | awk '{print $5}' | tr -d "\-MariaDB,")
        echo -e " \e[0;32mMariaDB-${Cur_MariaDB_Version} OK\e[0m"
        isDB="ok"
     else
        echo -e " \e[0;31mError: MariaDB install failed.\e[0m"
    fi

}

Check_PHP_Files()
{
    isPHP=""
    if [[ -s /usr/sbin/${PHPFPMProgram} && -s ${PHPConfigFile} && -s /usr/bin/php ]]; then
        Cur_PHP_Version=$(php -r 'echo PHP_VERSION;' 2>/dev/null | awk -F[~-] '{print $1}' )
        echo -e " \e[0;32mPHP-${Cur_PHP_Version} OK\e[0m"
        isPHP="ok"
     else
        echo -e " \e[0;31mError: PHP install failed.\e[0m"
    fi
}


Print_Sucess_Info()
{
    Moodle_Version=$( cat ${Default_Moodle_Dir}/moodle/version.php 2>/dev/null| grep Human-friendly | awk -F\' '{print $2}' | awk -F" " '{print $1}' )
    Debian_Version=$( cat /etc/debian_version )
    echo "------------------------------------------------------------------------"
    echo "       moodle ${Moodle_Version} for Debian ${Debian_Version} Linux Server, Written by Hong   "
    echo "                 http://hongm.emoodle.org                               "
    echo "------------------------------------------------------------------------"
    echo "  moodle manage: moodle {start|stop|reload|restart|kill|status|version} "
    echo "------------------------------------------------------------------------"
    echo "  Nginx:   systemctl {start|stop|reload|restart|status} nginx.service   "
    echo "  MariaDB: systemctl {start|stop|reload|restart|status} mysql.service   "
    echo "  PHP-FPM: systemctl {start|stop|reload|restart|status} ${PHPFPMService}.service"
    echo "------------------------------------------------------------------------"
    echo "  Moodle Web Site: http://${IP}                                            "
    echo "  Moodle Soucre directory: ${Default_Moodle_Dir}/moodle                 "
    echo "  Moodle Data directory: ${Default_Moodle_Dir}/moodledata               "
    echo "------------------------------------------------------------------------"
    echo "  Moodle admin password: ${DB_Root_PWD}                                "
    echo "------------------------------------------------------------------------"
    echo "  MariaDB root password: ${DB_Root_PWD}                                "
    echo "------------------------------------------------------------------------"
}

Print_Failed_Info()
{
    echo -e " \e[0;31mSorry,Failed to install LNMP!\e[0m"
    echo -e " \e[0;31mYou can download moodle-install.log from your server,and mail install.log to hongm@sina.com.\e[0m"
}

Check_Install()
{
    Check_Nginx_Files
    Check_DB_Files
    Check_PHP_Files
    if [[ "$isNginx" = "ok" && "$isDB" = "ok" && "$isPHP" = "ok" ]]; then
        Print_Sucess_Info
     else
        Print_Failed_Info
    fi
}


InstallLNMP 2>&1 | tee -a ${cur_dir}/moodle-install.log
InstallMoodle 2>&1 | tee -a ${cur_dir}/moodle-install.log
Check_Install 2>&1 | tee -a ${cur_dir}/moodle-install.log
